package com.lagou.client;

import com.lagou.model.ExamReport;
import com.lagou.model.Question;
import com.lagou.model.User;
import com.lagou.model.UserMessage;
import com.lagou.server.ServerDao;

import java.io.*;
import java.util.LinkedList;


public class ClientView {
    //用了合成复用原则
    private ClientInitClose cic;

    private ServerDao sd;

    /**
     * 通过构造方法实现成员变量的初始化
     * @param cic
     */
    public ClientView(ClientInitClose cic, ServerDao sd) {
        this.cic = cic;
        this.sd = sd;
    }

    /**
     * 自定义成员方法实现客户端主界面的绘制
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public void clientMainPage() throws IOException, ClassNotFoundException {
        while (true) {
            System.out.println("    \n\n\t\t在线考试系统");
            System.out.println("--------------------------------------");
            System.out.print(" [1] 学员系统");
            System.out.println("   [2] 管理员系统");
            System.out.println(" [0] 退出系统");
            System.out.println("--------------------------------------");
            System.out.println("请输入要选择的编号:");

            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    studentSystemPage();
                    break;
                case 2:
                    managerSystemPage();
                    break;
                case 0:
                    clientExit();
                    return;
                default:
                    System.out.println("输入错误，请重新输入！");
            }
        }
    }

    /**
     * 学员系统登陆界面
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void studentSystemPage() throws IOException, ClassNotFoundException {
        //判断是否登陆
        if (!clientStudentLogin()) {
            return;
        }
        //绘制学员系统的主界面和功能实现
        while(true) {
            System.out.println("    \n\n\t\t学员系统");
            System.out.println("-------------------------");
            System.out.print(" [1] 开始考试");
            System.out.println("   [2] 查询成绩");
            System.out.print(" [3] 导出成绩");
            System.out.println("   [4] 修改密码");
            System.out.println(" [0] 返回");
            System.out.println("--------------------------");
            System.out.println("请选择要进行的业务编号:");

            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    startTest();
                    break;
                case 2:
                    queryExamReport();
                    break;
                case 3:
                    saveExamReport();
                    break;
                case 4:
                    updatePassword();
                    break;
                case 0:
                    clientOut();
                    return;
                default:
                    System.out.println("输入错误，请重新输入！");
            }
        }
    }

    /**
     * 实现学员密码修改
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void updatePassword() throws IOException, ClassNotFoundException {
        //输入新密码
        System.out.println("请输入新密码：");
        String password = ClientScanner.getScanner().next();
        UserMessage userMessage = new UserMessage("updatePassword",new User("",password));

        //将密码发送给服务器
        cic.getOos().writeObject(userMessage);
        System.out.println("发送密码到服务器");

        //接收服务器传回的标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("密码修改成功");
        }else {
            System.out.println("密码修改失败");
        }
    }

    /**
     * 导出成绩
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void saveExamReport() throws IOException, ClassNotFoundException {
        //发送查询成绩的标识
        cic.getOos().writeObject(new UserMessage("saveExamReport",null));

        //接收服务器传回来的考试成绩
        ExamReport examReport = (ExamReport) cic.getOis().readObject();
        if (null == examReport) {
            System.out.println("暂无考试成绩");
            return;
        }

        /*sd.getCurrentUser().getUserName()*/
        //将成绩单保存到本地
        File file = new File("d:/在线考试系统/成绩单.txt");
        BufferedWriter bw = null;
        try {
            if (!file.exists()) {
                System.out.println(file.createNewFile() ? "成绩单创建成功" : "成绩单创建失败");
            }else {
                System.out.println("成绩单已存在，将会覆盖原文件");
            }

            bw = new BufferedWriter(new FileWriter(file));
            bw.write(examReport.toString());
            bw.flush();
            System.out.println("成绩单导出成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 查询成绩
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void queryExamReport() throws IOException, ClassNotFoundException {
        //发送查询成绩的标识
        cic.getOos().writeObject(new UserMessage("saveExamReport",null));

        //接收服务器传回来的考试成绩
        ExamReport examReport = (ExamReport) cic.getOis().readObject();
        if (null == examReport) {
            System.out.println("暂无考试成绩");
            return;
        }

        //打印考试成绩
        System.out.println(examReport);
    }

    /**
     * 学员开始考试功能
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void startTest() throws IOException, ClassNotFoundException {
        //向服务器发送开始考试标识
        cic.getOos().writeObject(new UserMessage("startTest",null));

        //接收服务器返回的考试题
        String[] examQuestions = (String[]) cic.getOis().readObject();
        if (null == examQuestions) {
            System.out.println("系统暂无考题，请稍后再试");
            return;
        }

        //开始考试，读取答案
        System.out.println("    \n\n\t\t开始考试\n");
        String[] examAnswer = new String[3];
        for (int i = 0; i < examAnswer.length; i++) {
            System.out.println("第" + (i + 1) + "题");
            System.out.println(examQuestions[i]);
            System.out.print("请输入答案：");
            examAnswer[i] = ClientScanner.getScanner().next();
            System.out.println();
        }

        //将答案发送给服务器
        cic.getOos().writeObject(examAnswer);
        System.out.println("考试结束！");
    }

    /**
     * 发送退出消息到服务器
     *
     * @throws IOException
     */
    private void clientOut() throws IOException {
        UserMessage userMessage = new UserMessage("clientOut",null);
        cic.getOos().writeObject(userMessage);
        System.out.println("发送退出消息到服务器");
    }

    /**
     * 发送退出消息到服务器
     *
     * @throws IOException
     */
    private void clientExit() throws IOException {
        UserMessage userMessage = new UserMessage("clientExit",null);
        cic.getOos().writeObject(userMessage);
        System.out.println("发送退出消息到服务器");
    }

    /**
     * 客户端学员登陆
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private boolean clientStudentLogin() throws IOException, ClassNotFoundException {
        //准备学员登陆的相关数据
        System.out.println("请输入学员用户名：");
        String userName = ClientScanner.getScanner().next();
        System.out.println("请输入学员密码：");
        String password = ClientScanner.getScanner().next();
        UserMessage um = new UserMessage("userCheck", new User(userName, password));

        //将UserMessage对象发送给服务器
        cic.getOos().writeObject(um);
        System.out.println("客户端发送管理员信息成功");

        //接收服务器的结果并提示
        um = (UserMessage) cic.getOis().readObject();
        if ("success".equals(um.getType())) {
            System.out.println("登陆成功，欢迎使用");
            return true;
        }else {
            System.out.println("账号或用户名密码错误");
            return false;
        }
    }

    /**
     * 管理员系统界面
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void managerSystemPage() throws IOException, ClassNotFoundException {
        //判断是否登陆
        if (!clientManagerLogin()) {
            return;
        }
        //绘制管理员系统的主界面和功能实现
        while(true) {
            System.out.println("    \n\n\t\t管理员系统");
            System.out.println("-------------------------");
            System.out.print(" [1] 学员管理");
            System.out.println("   [2] 考题管理");
            System.out.println(" [0] 返回");
            System.out.println("--------------------------");
            System.out.println("请选择要进行的业务编号:");

            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    manageStudentInfoPage();
                    break;
                case 2:
                    manageExamInfoPage();
                    break;
                case 0:
                    clientOut();
                    return;
                default:
                    System.out.println("输入错误，请重新输入！");
            }
        }
    }

    /**
     * 考题管理界面
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void manageExamInfoPage() throws IOException, ClassNotFoundException {
        while (true) {
            System.out.println("    \n\n\t\t考题管理");
            System.out.println("-----------------------");
            System.out.print(" [1] 增加考题");
            System.out.println("   [2] 删除考题");
            System.out.print(" [3] 修改考题");
            System.out.println("   [4] 查找考题");
            System.out.print(" [5] 导入考题");
            System.out.println("   [0] 返回");
            System.out.println("-----------------------");
            System.out.println("请输入要进行的业务编码");

            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    addQuestion();
                    break;
                case 2:
                    deleteQuestion();
                    break;
                case 3:
                    updateQuestion();
                    break;
                case 4:
                    searchQuestion();
                    break;
                case 5:
                    loadQuestion();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入错误，请重新输入！");
            }
        }
        
    }

    /**
     * 导入考题
     */
    private void loadQuestion() {
        File file = new File("d:/在线考试系统/考题.txt");
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }

        //初始化文件输入流
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            LinkedList<Question> questions = new LinkedList<>();

            //读取考题并加入集合
            int num = Integer.parseInt(br.readLine());
            String question, a, b, c, d, answer;
            for (int i = 0; i < num; i++) {
                question = br.readLine();
                a = br.readLine();
                b = br.readLine();
                c = br.readLine();
                d = br.readLine();
                answer = br.readLine();
                questions.add(new Question(question + "\nA." + a + "\nB." + b + "\nC." + c + "\nD." + d, answer));
            }

            //向服务器发送导入考题标识
            cic.getOos().writeObject(new UserMessage("loadQuestion",null));

            //将考题发给服务器
            cic.getOos().writeObject(questions);

            //从服务器读取标识
            UserMessage userMessage = (UserMessage) cic.getOis().readObject();
            if ("success".equals(userMessage.getType())) {
                System.out.println("考题导入成功");
            }else {
                System.out.println("考题导入失败");
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 查找考题
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void searchQuestion() throws IOException, ClassNotFoundException {
        //输入要查找的内容
        System.out.println("请输入要查找的考题内容：");
        String question = ClientScanner.getScanner().next();

        //向服务器发送查找标识
        cic.getOos().writeObject(new UserMessage("searchQuestion",null));

        //向服务器发送要查找的问题
        cic.getOos().writeObject(question);

        //从服务器读取考题
        Question q = (Question) cic.getOis().readObject();
        if (null != q) {
            System.out.println("考题如下：");
            System.out.println(q);
        }else {
            System.out.println("考题查找失败");
        }
    }

    /**
     * 修改考题
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void updateQuestion() throws IOException, ClassNotFoundException {
        //输入考题内容
        System.out.println("请输入要修改的问题：");
        String question = ClientScanner.getScanner().next();
        System.out.println("请输入修改后选项内容：");
        System.out.print("A.");
        String a = ClientScanner.getScanner().next();
        System.out.print("B.");
        String b = ClientScanner.getScanner().next();
        System.out.print("C.");
        String c = ClientScanner.getScanner().next();
        System.out.print("D.");
        String d = ClientScanner.getScanner().next();
        System.out.print("答案：");
        String answer = ClientScanner.getScanner().next();

        //向服务器发送增加考题标识
        UserMessage userMessage = new UserMessage("updateQuestion",null);
        cic.getOos().writeObject(userMessage);

        //向服务器发送修改的考题内容和答案
        cic.getOos().writeObject(question);
        cic.getOos().writeObject("\nA." + a + "\nB." + b + "\nC." + c + "\nD." + d);
        cic.getOos().writeObject(answer);

        //从服务器读取标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("考题修改成功");
        }else {
            System.out.println("考题修改失败");
        }
    }

    /**
     * 删除考题
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void deleteQuestion() throws IOException, ClassNotFoundException {
        //输入要删除的内容
        System.out.println("请输入要删除的考题：");
        String question = ClientScanner.getScanner().next();

        //向服务器发送删除考题标识
        UserMessage userMessage = new UserMessage("deleteQuestion",null);
        cic.getOos().writeObject(userMessage);

        //向服务器发送考题
        cic.getOos().writeObject(question);

        //从服务器读取标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("考题删除成功");
        }else {
            System.out.println("考题删除失败");
        }
    }

    /**
     * 增加考题
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void addQuestion() throws IOException, ClassNotFoundException {
        //输入考题内容
        System.out.println("请输入问题：");
        String question = ClientScanner.getScanner().next();
        System.out.println("请输入选项内容：");
        System.out.print("A.");
        String a = ClientScanner.getScanner().next();
        System.out.print("B.");
        String b = ClientScanner.getScanner().next();
        System.out.print("C.");
        String c = ClientScanner.getScanner().next();
        System.out.print("D.");
        String d = ClientScanner.getScanner().next();
        System.out.print("答案：");
        String answer = ClientScanner.getScanner().next();

        Question q = new Question(question + "\nA." + a + "\nB." + b + "\nC." + c + "\nD." + d, answer);

        //向服务器发送增加考题标识
        UserMessage userMessage = new UserMessage("addQuestion",null);
        cic.getOos().writeObject(userMessage);

        //向服务器发送考题
        cic.getOos().writeObject(q);

        //从服务器读取标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("考题增加成功");
        }else {
            System.out.println("考题增加失败");
        }
    }

    /**
     * 学员管理模块
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void manageStudentInfoPage() throws IOException, ClassNotFoundException {
        while (true) {
            System.out.println("    \n\n\t\t学员管理");
            System.out.println("-----------------------");
            System.out.print(" [1] 添加学员");
            System.out.println("   [2] 删除学员");
            System.out.print(" [3] 修改学员");
            System.out.println("   [4] 查找学员");
            System.out.print(" [5] 遍历学员");
            System.out.println("   [0] 返回");
            System.out.println("-----------------------");
            System.out.println("请输入要进行的业务编码");

            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    addStudent();
                    break;
                case 2:
                    deleteStudent();
                    break;
                case 3:
                    updateStudent();
                    break;
                case 4:
                    searchStudent();
                    break;
                case 5:
                    findAllStudent();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入错误，请重新输入！");
            }
        }
    }

    /**
     * 遍历系统内的学员
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void findAllStudent() throws IOException, ClassNotFoundException {
        //传给服务器
        cic.getOos().writeObject(new UserMessage("findAllStudent",null));
        System.out.println("发送要遍历学员标识到服务器");

        //接收服务器返回的学员信息
        LinkedList<User> userLinkedList = (LinkedList<User>) cic.getOis().readObject();
        if (userLinkedList.isEmpty()) {
            System.out.println("提示：系统暂无学员信息");;
        }else {
            userLinkedList.forEach(System.out::println);
        }
    }

    /**
     * 实现学员的查找
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void searchStudent() throws IOException, ClassNotFoundException {
        //输入要查找的学员名
        System.out.println("请输入要查找的学员的用户名：");
        String userName = ClientScanner.getScanner().next();
        UserMessage userMessage = new UserMessage("searchStudent", new User(userName,""));

        //传给服务器
        cic.getOos().writeObject(userMessage);
        System.out.println("发送要查找的学员的用户名到服务器");

        //从服务器读取标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("查找成功" + userMessage.getUser());
        }else {
            System.out.println("查找失败，学员或不存在");
        }
    }

    /**
     * 实现学员的更新
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void updateStudent() throws IOException, ClassNotFoundException {
        //输入要更新的学员名
        System.out.println("请输入要更新的学员的用户名：");
        String userName = ClientScanner.getScanner().next();
        System.out.println("请输入要更新的学员的密码：");
        String password = ClientScanner.getScanner().next();
        UserMessage userMessage = new UserMessage("updateStudent", new User(userName,password));

        //传给服务器
        cic.getOos().writeObject(userMessage);
        System.out.println("发送要更新的学员的信息到服务器");

        //从服务器读取标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("更新成功");
        }else {
            System.out.println("更新失败，学员或不存在");
        }
    }

    /**
     * 实现学员的删除
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void deleteStudent() throws IOException, ClassNotFoundException {
        //输入要删除的学员名
        System.out.println("请输入要删除的学员的用户名：");
        String userName = ClientScanner.getScanner().next();
        UserMessage userMessage = new UserMessage("deleteStudent", new User(userName,""));

        //传给服务器
        cic.getOos().writeObject(userMessage);
        System.out.println("发送要删除的学员的用户名到服务器");

        //从服务器读取标识
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败，学员或不存在");
        }
    }

    /**
     * 实现学员增加功能
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void addStudent() throws IOException, ClassNotFoundException {
        //输入新学员的数据
        System.out.println("请输入新学员的用户名");
        String userName = ClientScanner.getScanner().next();
        System.out.println("请输入新学员的密码");
        String password = ClientScanner.getScanner().next();
        UserMessage userMessage = new UserMessage("addStudent", new User(userName, password));

        //将userMessage对象发送给服务器
        cic.getOos().writeObject(userMessage);
        System.out.println("发送新增学员的信息给服务器");

        //接收服务器处理结果
        userMessage = (UserMessage) cic.getOis().readObject();
        if ("success".equals(userMessage.getType())) {
            System.out.println("学员增加成功");
        }else {
            System.out.println("学员增加失败");
        }
    }

    /**
     * 客户端管理员登陆功能
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public boolean clientManagerLogin() throws IOException, ClassNotFoundException {
        //准备管理员登陆的相关数据
        System.out.println("请输入管理员用户名：");
        String userName = ClientScanner.getScanner().next();
        System.out.println("请输入管理员密码：");
        String password = ClientScanner.getScanner().next();
        UserMessage um = new UserMessage("managerCheck", new User(userName, password));

        //将UserMessage对象发送给服务器
        cic.getOos().writeObject(um);
        System.out.println("客户端发送管理员信息成功");

        //接收服务器的结果并提示
        um = (UserMessage) cic.getOis().readObject();
        if ("success".equals(um.getType())) {
            System.out.println("登陆成功，欢迎使用");
            return true;
        }else {
            System.out.println("账号或用户名密码错误");
            return false;
        }
    }
}
